<?php
/**
 * PaypalService.php
 *
 * @copyright  2023 beikeshop.com - All Rights Reserved
 * @link       https://beikeshop.com
 * @author     Edward Yang <yangjin@guangda.work>
 * @created    2023-08-22 11:49:51
 * @modified   2023-08-22 11:49:51
 */

namespace Plugin\Wooshpay\Services;
use Illuminate\Http\Request;
use Beike\Shop\Services\PaymentService;
use GuzzleHttp\Exception\GuzzleException;
use Srmklive\PayPal\Services\PayPal;
use Illuminate\Support\Facades\Log;


use GuzzleHttp\Client;
class WooshpayService extends PaymentService
{
    public PayPal $paypalClient;

    protected array $serverUrl;

    protected array $wooshpaySetting;
    protected Client $client;

    protected Request $request;
    /**
     * @param             $order
     * @throws \Exception
     * @throws \Throwable
     */
    public function __construct($order)
    {

        parent::__construct($order);

        $this->wooshpaySetting = plugin_setting('wooshpay');
        $this->request =  Request::capture();

        // 初始化服务器URL配置
        $this->serverUrl = [
            'apitest' => 'https://apitest.wooshpay.com',
            'api' => 'https://api.wooshpay.com'
        ];

        $username = $this->wooshpaySetting['wooshpay_key'];
        $password = "";
        $Basic = base64_encode("{$username}:{$password}");

        $this->client  = new Client([
            'base_uri'  =>  $this->serverUrl[$this->wooshpaySetting['api_mode']],
            'headers'   =>  [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization'   =>  "Basic {$Basic}"
            ],
            // 明确设置超时和禁用重试，防止重复请求
            'timeout' => 30,
            'connect_timeout' => 10,
            'http_errors' => true,
            // 禁用默认的重试机制
            'retry' => false
        ]);
        $this->initWooshpay();
    }

    private function initWooshpay() : void
    {

    }

    /**
     * 创建 Wooshpay Checkout Session
     *
     * 根据 Wooshpay API 文档创建支付会话
     * API 端点: POST /v1/checkout/sessions
     * 文档参考: https://docs.wooshpay.com/doc-1722914#create-checkout
     *
     * @param array $data 请求数据（当前未使用，保留用于扩展）
     * @return array 返回创建结果，包含 Checkout Session 的 URL 和相关信息
     */
    public function createOrder( array $data ){
        try {
            Log::info('Wooshpay createOrder 开始执行', [
                'order_number' => $this->order->number,
                'request_data' => $data,
                'timestamp' => now()->toDateTimeString()
            ]);

            // 构建当前域名，用于生成回调 URL
            $http = $this->request->getScheme()  ."://" . $this->request->getHost();

            // 构建 Wooshpay Checkout Session 请求参数
            // 参考文档: https://docs.wooshpay.com/doc-1722914#create-checkout
            $array = [
                // 取消支付后的重定向 URL - 用户点击取消或支付失败时跳转
                "cancel_url" => "{$http}/orders/{$this->order->number}/pay?from_payment=true&status=cancelled",

                // 支付模式 - "payment" 表示一次性支付
                "mode" => "payment",

                // 支付成功后的重定向 URL
                // 注意：success_url 不能作为判断支付成功的唯一条件
                // 应该以 Checkout 对象状态和对应的 PaymentIntent 状态为准
                "success_url" => "{$http}/orders/{$this->order->number}/pay?from_payment=true&status=success",

                // 商品项目列表 - 定义要收费的商品
                "line_items" => [
                    [
                        "price_data" => [
                            // 货币类型，使用订单的货币代码
                            "currency" => $this->order->currency_code,

                            // 单价金额，以最小货币单位表示（如分）
                            // 将订单总额乘以100转换为分
                            "unit_amount" => (int)($this->order->total * 100),

                            // 商品数据
                            "product_data" => [
                                // 商品名称，使用客户姓名作为标识
                                "name" => $this->order->customer_name,
                            ]
                        ],
                        // 购买数量
                        "quantity" => 1
                    ]
                ],

                // PaymentIntent 相关数据 - 包含订单和收货信息
                "payment_intent_data"   =>  [
                    // 收货地址信息
                    "shipping"  =>  [
                        "address"   => [
                            'city' => $this->order->shipping_city,
                            'line1' => $this->order->shipping_country . $this->order->shipping_zone,
                        ],
                        'name' => $this->order->shipping_customer_name,
                        'phone' => $this->order->shipping_telephone // 收件人电话
                    ],
                    'merchant_user_id' => $this->order->customer_id, // 商户用户ID，用于关联客户
                    'merchant_order_id' => $this->order->number, // 商户订单ID，用于 Webhook 回调识别订单
                ]
            ];

            // 生成幂等性密钥，确保同一订单不会创建重复的支付会话
            // 使用订单号和订单总额作为幂等性密钥的基础，确保唯一性
            $idempotencyKey = 'checkout_' . $this->order->number . '_' . md5($this->order->total . $this->order->currency_code);

            Log::info('Wooshpay createOrder 准备发送API请求', [
                'order_number' => $this->order->number,
                'idempotency_key' => $idempotencyKey,
                'order_total' => $this->order->total,
                'currency' => $this->order->currency_code,
                'api_url' => $this->serverUrl[$this->wooshpaySetting['api_mode']] . '/v1/checkout/sessions',
                'request_payload' => $array
            ]);

            // 调用 Wooshpay API 创建 Checkout Session
            // 添加 Idempotency-Key 头部防止重复创建支付会话
            $response = $this->client->request("POST" , "/v1/checkout/sessions" , [
                "json"  =>  $array,
                "headers" => [
                    "Idempotency-Key" => $idempotencyKey
                ]
            ]);

            Log::info('Wooshpay createOrder API请求成功', [
                'order_number' => $this->order->number,
                'idempotency_key' => $idempotencyKey,
                'response_status' => $response->getStatusCode()
            ]);

            // 返回成功响应，包含 Checkout Session 数据
            // 响应中的 'url' 字段是客户需要重定向到的支付页面 URL
            return [
                'code'  =>  1,
                'message' => 'success',
                'data'    => json_decode($response->getBody()->getContents() , true)
            ];
        } catch (\GuzzleHttp\Exception\ConnectException $e) {
            // 网络连接异常，没有响应
            Log::error('Wooshpay createOrder ConnectException', [
                'message' => $e->getMessage(),
                'order_number' => $this->order->number
            ]);
            return [
                'code'  => 0,
                'message' => trans('Wooshpay::setting.network_connection_failed'),
                'error' => $e->getMessage()
            ];
        } catch (\GuzzleHttp\Exception\ClientException | \GuzzleHttp\Exception\ServerException $e) {
            // 有响应的异常（4xx 或 5xx 状态码）
            $response = $e->getResponse();
            $statusCode = $response? $response->getStatusCode() : '未知';
            $responseBody = $response? $response->getBody()->getContents() : '未知';
            Log::error('Wooshpay createOrder ClientException', [
                'status_code' => $statusCode,
                'response_body' => $responseBody,
                'order_number' => $this->order->number
            ]);
            return [
                'code'  =>  $statusCode,
                'message' => trans('Wooshpay::setting.payment_service_error'),
                'error' => $responseBody
            ];
        }
    }

    /**
     * 获取移动端支付参数
     * 为了兼容Bootstrap中的钩子，添加此方法
     *
     * @return array
     * @throws \Exception
     */
    public function getMobilePaymentData(): array
    {
        // 对于Wooshpay，移动端和Web端使用相同的Checkout Session
        // 所以我们创建一个Checkout Session并返回相关参数
        $result = $this->createOrder([]);

        if ($result['code'] !== 1) {
            throw new \Exception('Failed to create Wooshpay checkout session: ' . ($result['message'] ?? 'Unknown error'));
        }

        return [
            'checkout_url' => $result['data']['url'] ?? '',
            'session_id' => $result['data']['id'] ?? '',
            'payment_intent' => $result['data']['payment_intent'] ?? ''
        ];
    }

//
//    public function createOrder( array $params ) : array
//    {
//        return $this->payment_intents($params);
//    }
//
//    public function confirmOrder( array $params ) : array
//    {
//        return ['errCode'=>200 , 'data' => $params];
//    }
//
//
    /**
     * 确认支付结果 - 查询 Checkout Session 状态
     *
     * 根据 Wooshpay 文档，有两种方式获取支付结果：
     * 1. 通过 Webhook 获取支付结果（推荐）- 监听 'payment_intent.succeeded' 等事件
     * 2. 通过 API 查询 PaymentIntent 状态（本方法实现）
     *
     * 此方法查询 Checkout Session 的当前状态，包含关联的 PaymentIntent 信息
     * API 端点: GET /v1/checkout/sessions/{id}
     *
     * @param array $order 包含 Checkout Session ID 的数组
     * @return array 返回 Checkout Session 的详细信息，包括支付状态
     */
    public  function confirm( array $order) : array
    {
        try {
            // 获取 Checkout Session ID
            $id = $order['id'];

            Log::info('Wooshpay confirm payment session', [ //支付会话
                'session_id' => $id,
                'order_number' => $this->order->number
            ]);

            try {
                // 调用 Wooshpay API 查询 Checkout Session 状态
                // 这将返回 Session 的完整信息，包括关联的 PaymentIntent 状态
                $response = $this->client->request('GET', "/v1/checkout/sessions/{$id}");
                $responseData = json_decode($response->getBody()->getContents(), true);

                \Log::info('Wooshpay session response', [ //会话响应
                    'session_id' => $id,
                    'response' => $responseData,
                    'order_number' => $this->order->number
                ]);

                // 添加成功标识，用于上层逻辑判断 API 调用是否成功
                $responseData['errCode'] = 200;
                return $responseData;

            } catch (GuzzleException $e) {
                // Guzzle HTTP 异常处理
                \Log::error('Wooshpay confirm GuzzleException', [
                    'session_id' => $id,
                    'error' => $e->getMessage(),
                    'order_number' => $this->order->number
                ]);
                return ['errCode' => 0, 'message' => $e->getMessage()];
            }

        } catch (\GuzzleHttp\Exception\ClientException $e) {
            // 客户端异常（4xx 状态码）
            $response = $e->getResponse();
            $statusCode = $response? $response->getStatusCode() : '未知';
            $responseBody = $response? $response->getBody()->getContents() : '未知';

            \Log::error('Wooshpay confirm ClientException', [
                'status_code' => $statusCode,
                'response_body' => $responseBody,
                'order_number' => $this->order->number
            ]);

            return [
                'errCode'  =>  $statusCode,
                'message' => trans('Wooshpay::setting.payment_query_failed'),
                'error' => $responseBody
            ];
        }
    }
//
//
//    private function payment_intents( array $order )
//    {
//
//        $orderid = $this->order->number;
//
//        $http = $this->request->getScheme()  ."://" . $this->request->getHost() . "/" . 'orders/'.$orderid.'/pay?pay=check';
//
//        $expiry = explode('-', $order['expiry']);
//        // 构建请求体数据
//        $requestData = [
//            'amount' => (int)($this->order->total * 100), // 支付金额，以最小货币单位表示
//            'currency' => $this->order->currency_code, // 货币类型
//            'confirm' => true, // 是否立即确认支付意图
//            'payment_method_data' => [
//                'type' => 'card', // 支付方式类型为银行卡
//                'card' => [
//                    'exp_month' => $expiry[1], // 信用卡过期月份
//                    'exp_year' => $expiry[0], // 信用卡过期年份
//                    'number' => $order['cardNumber'], // 信用卡卡号
//                    'cvc' => $order['cvc'] // 信用卡安全码
//                    ,'name'=> $order['name']
//                ],
////                'billing_details' => [
////                    'address' => [
////                        'line1' => $this->order->shipping_country . $this->order->shipping_zone,
////                        'line2' => $this->order->shipping_address_1,
////                        'city' => $this->order->shipping_city,
////
////                    ],
////                    'name' => $this->order->shipping_customer_name,
////                ]
//            ],
////            'description' => 'product description', // 订单描述
////            'quantity' => 1, // 购买数量
////            'metadata' => [
////                'key1' => 'value1' // 自定义元数据
////            ],
//            'merchant_user_id' => $this->order->customer_id, // 商户用户ID
//            'merchant_order_id' => $this->order->number, // 商户订单ID
//            'shipping' => [
//                'address' => [
//                    'line1' => $this->order->shipping_country . $this->order->shipping_zone,
//                    'line2' => $this->order->shipping_address_1,
//                    'city' => $this->order->shipping_city,
//                ],
//                'name' => $this->order->shipping_customer_name,
////                'phone' => $this->order->shipping_telephone // 收件人电话
//            ],
//            'return_url' => $http // 支付完成或取消后重定向的URL
//        ];
//        try {
//
//            $response = $this->client->request('POST' , '/v1/payment_intents' , [
//                'json'  => $requestData,
//
//            ]);
//
//            return ['errCode'=>200, 'message' => '请求成功' ,'data'=> json_decode($response->getBody()->getContents() , true)];
//        } catch (\GuzzleHttp\Exception\ClientException $e) {

//        }
//    }

}
